// 存储过滤配置
let settings = {
  enableFilter: true,
  minImages: 1,
  autoRefresh: true
};

// 弹窗状态跟踪
let popupState = {
  isImagesTabActive: false,
  autoRefreshEnabled: true
};

// 过滤计数器
let filteredCount = 0;

// 画廊数据存储
let galleryData = {};

// 防抖和内存管理
let debounceTimer = null;
let isUpdating = false;
let eventListeners = new Set();

// 防抖函数
function debounce(func, wait) {
  return function executedFunction(...args) {
    const later = () => {
      debounceTimer = null;
      func(...args);
    };
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(later, wait);
  };
}

// 清理事件监听器
function addEventListenerWithCleanup(element, event, handler, options) {
  element.addEventListener(event, handler, options);
  eventListeners.add({ element, event, handler });
}

// 移除所有事件监听器
function removeAllEventListeners() {
  eventListeners.forEach(({ element, event, handler }) => {
    try {
      element.removeEventListener(event, handler);
    } catch (e) {
      console.warn('Failed to remove event listener:', e);
    }
  });
  eventListeners.clear();
}

// 清理画廊数据
function clearGalleryData() {
  const imageCount = galleryData.allImages ? galleryData.allImages.length : 0;
  galleryData = {};
  
  // 强制垃圾回收（如果可用）
  if (window.gc) {
    window.gc();
  }
  
  console.log(`已清理沉浸看图数据，释放 ${imageCount} 张图片的内存`);
}

// 内存监控函数
function checkMemoryUsage() {
  if (performance.memory) {
    const memory = performance.memory;
    const usedMB = Math.round(memory.usedJSHeapSize / 1024 / 1024);
    const limitMB = Math.round(memory.jsHeapSizeLimit / 1024 / 1024);
    
    console.log(`内存使用: ${usedMB}MB / ${limitMB}MB`);
    
    // 如果内存使用超过80%，主动清理
    if (usedMB / limitMB > 0.8) {
      console.warn('内存使用过高，开始清理...');
      clearGalleryData();
      removeAllEventListeners();
      
      // 如果还是很高，关闭画廊
      setTimeout(() => {
        if (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit > 0.8) {
          hideGallery();
          alert('内存使用过高，已自动关闭画廊模式');
        }
      }, 1000);
    }
  }
}

// 加载配置
chrome.storage.sync.get({
  enableFilter: true,
  minImages: 1,
  autoRefresh: true
}, (items) => {
  settings = items;
  popupState.autoRefreshEnabled = items.autoRefresh;
});

// 监听配置更新
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'SETTINGS_UPDATED') {
    settings = message.settings;
    // 重新应用过滤器
    applyFilter();
  } else if (message.type === 'COLLECT_IMAGES') {
    // 响应popup请求收集图片
    console.log('[图片收集] 收到popup请求，开始收集图片...');
    collectGalleryData();
    
    // 返回图片数据给popup
    chrome.runtime.sendMessage({
      images: galleryData.allImages || []
    });
  } else if (message.type === 'IMAGES_TAB_STATUS') {
    // 更新弹窗状态
    popupState.isImagesTabActive = message.isActive;
    popupState.autoRefreshEnabled = message.autoRefresh;
    console.log('[自动刷新] 弹窗状态更新:', popupState);
  } else if (message.type === 'AUTO_REFRESH_UPDATED') {
    // 更新自动刷新设置
    popupState.autoRefreshEnabled = message.autoRefresh;
    settings.autoRefresh = message.autoRefresh;
    console.log('[自动刷新] 设置更新:', message.autoRefresh);
  }
});

// 检查回答是否包含足够的图片（原始简单逻辑）
function hasEnoughImages(answerElement) {
  const images = answerElement.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar)');
  return images.length >= settings.minImages;
}

// 提取作者信息
function extractAuthorInfo(answerElement) {
  const authorInfo = {
    name: '未知作者',
    avatar: '',
    url: ''
  };

  // 尝试多种选择器来获取作者信息
  const authorElement = answerElement.querySelector('.AuthorInfo-head') || 
                       answerElement.querySelector('.AuthorInfo') ||
                       answerElement.querySelector('.UserLink-link');
  
  if (authorElement) {
    // 获取作者姓名
    const nameElement = authorElement.querySelector('.UserLink-link') ||
                       authorElement.querySelector('.AuthorInfo-name') ||
                       authorElement.querySelector('[data-tooltip*="个人页面"]');
    
    if (nameElement) {
      authorInfo.name = nameElement.textContent.trim() || nameElement.title || '未知作者';
      authorInfo.url = nameElement.href || '';
    }

    // 获取作者头像
    const avatarElement = authorElement.querySelector('.Avatar') ||
                         authorElement.querySelector('.AuthorInfo-avatar img') ||
                         authorElement.querySelector('img[src*="avatar"]');
    
    if (avatarElement) {
      authorInfo.avatar = avatarElement.src || '';
    }
  }

  return authorInfo;
}

// 提取回答中的图片信息
function extractImagesFromAnswer(answerElement, authorInfo) {
  const images = answerElement.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar)');
  const imageData = [];

  images.forEach((img, index) => {
    if (img.src && img.src !== '') {
      imageData.push({
        src: img.src,
        alt: img.alt || '',
        index: index,
        authorName: authorInfo.name,
        authorAvatar: authorInfo.avatar
      });
    }
  });

  return imageData;
}

// 收集所有图片数据（纯图片模式，不分组）
function collectGalleryData() {
  console.log('[沉浸看图] 开始收集图片数据...');
  
  // 内存保护：清理旧数据
  galleryData = { allImages: [] };
  
  // 尝试多种选择器以提高兼容性
  const possibleSelectors = [
    '.List-item',           // 原有选择器
    '.Question-mainColumn .List .List-item',  // 更具体的路径
    '[data-zop-question-answer]',  // 可能的属性选择器
    '.AnswerItem',          // 另一种可能的类名
    '.Card.AnswerCard'      // 卡片式布局
  ];
  
  let answers = null;
  let usedSelector = '';
  
  for (const selector of possibleSelectors) {
    const elements = document.querySelectorAll(selector);
    if (elements.length > 0) {
      answers = elements;
      usedSelector = selector;
      console.log(`[沉浸看图] 使用选择器 "${selector}" 找到 ${elements.length} 个回答容器`);
      break;
    }
  }
  
  if (!answers || answers.length === 0) {
    console.warn('[沉浸看图] 未找到任何回答容器，尝试查找所有图片...');
    // 如果找不到回答容器，直接查找页面中的所有图片
    const allImages = document.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar):not([src*="avatar"]):not([alt*="头像"])');
    console.log(`[沉浸看图] 页面中找到 ${allImages.length} 张图片`);
    
    allImages.forEach((img, index) => {
      if (img.src && img.src !== '' && !img.src.includes('data:image/svg') && img.offsetWidth > 100 && img.offsetHeight > 100) {
        galleryData.allImages.push({
          src: img.src,
          alt: img.alt || '',
          index: index
        });
      }
    });
    
    console.log(`[沉浸看图] 直接收集完成: ${galleryData.allImages.length} 张有效图片`);
    return galleryData;
  }
  
  let totalImages = 0;
  let processedAnswers = 0;
  
  answers.forEach((item, answerIndex) => {
    // 内存保护：限制单次处理的图片数量
    if (totalImages > 1000) {
      console.warn('[沉浸看图] 图片数量过多，停止收集以保护内存');
      return;
    }
    
    // 尝试多种内容选择器
    const contentSelectors = ['.RichContent', '.AnswerItem-content', '.QuestionAnswer-content', '.Card-content'];
    let contentElement = null;
    
    for (const selector of contentSelectors) {
      contentElement = item.querySelector(selector);
      if (contentElement) break;
    }
    
    if (!contentElement) {
      // 如果找不到内容容器，直接使用回答容器
      contentElement = item;
    }
    
    const images = contentElement.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar):not([src*="avatar"]):not([alt*="头像"])');
    console.log(`[沉浸看图] 回答 ${answerIndex + 1}: 找到 ${images.length} 张图片`);
    
    if (images.length >= Math.max(1, settings.minImages || 1)) {
      images.forEach((img, index) => {
        // 更严格的图片过滤
        if (img.src && 
            img.src !== '' && 
            !img.src.includes('data:image/svg') &&
            !img.src.includes('loading.gif') &&
            img.offsetWidth > 50 && 
            img.offsetHeight > 50) {
          galleryData.allImages.push({
            src: img.src,
            alt: img.alt || '',
            index: totalImages + index,
            answerIndex: answerIndex
          });
        }
      });
      
      totalImages += images.length;
      processedAnswers++;
    }
  });

  // 详细的结果日志
  console.log(`[沉浸看图] 数据收集完成:`);
  console.log(`  - 使用选择器: ${usedSelector}`);
  console.log(`  - 检查回答数: ${answers.length}`);
  console.log(`  - 有图片回答: ${processedAnswers}`);
  console.log(`  - 有效图片数: ${galleryData.allImages.length}`);
  console.log(`  - 最少图片要求: ${settings.minImages || 1}`);
  
  return galleryData;
}

// 注意：画廊界面相关代码已移除，图片展示现在在弹窗中进行

// 诊断页面状态
function diagnosePageStatus() {
  const result = {
    pageType: '未知',
    answerCount: 0,
    totalImages: 0,
    url: window.location.href
  };
  
  // 判断页面类型
  if (result.url.includes('/question/')) {
    result.pageType = '问题页面';
  } else if (result.url.includes('/answer/')) {
    result.pageType = '回答页面';
  } else if (result.url.includes('/zhuanlan/')) {
    result.pageType = '专栏文章';
  } else {
    result.pageType = '其他页面';
  }
  
  // 统计回答数量
  const possibleSelectors = ['.List-item', '.AnswerItem', '.Card.AnswerCard'];
  for (const selector of possibleSelectors) {
    const elements = document.querySelectorAll(selector);
    if (elements.length > 0) {
      result.answerCount = elements.length;
      break;
    }
  }
  
  // 统计图片数量
  const allImages = document.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar)');
  result.totalImages = allImages.length;
  
  console.log('[沉浸看图] 页面诊断结果:', result);
  return result;
}

// 手动调试功能 - 在控制台输入 zhihuDebug() 调用
window.zhihuDebug = function() {
  console.log('=== 知乎图片过滤器调试信息 ===');
  
  // 基本信息
  console.log('1. 基本设置:');
  console.log('  - enableFilter:', settings.enableFilter);
  console.log('  - enableGallery:', settings.enableGallery);
  console.log('  - minImages:', settings.minImages);
  
  // 页面诊断
  console.log('2. 页面诊断:');
  const diagnostic = diagnosePageStatus();
  console.log('  - 页面类型:', diagnostic.pageType);
  console.log('  - URL:', diagnostic.url);
  console.log('  - 回答数量:', diagnostic.answerCount);
  console.log('  - 总图片数:', diagnostic.totalImages);
  
  // DOM选择器测试
  console.log('3. DOM选择器测试:');
  const selectors = [
    '.List-item',
    '.Question-mainColumn .List .List-item',
    '[data-zop-question-answer]',
    '.AnswerItem',
    '.Card.AnswerCard'
  ];
  
  selectors.forEach(selector => {
    const elements = document.querySelectorAll(selector);
    console.log(`  - ${selector}: ${elements.length} 个元素`);
  });
  
  // 手动收集图片
  console.log('4. 手动收集图片:');
  const oldGalleryData = { ...galleryData };
  collectGalleryData();
  console.log(`  - 收集到图片: ${galleryData.allImages.length} 张`);
  
  // 显示前几张图片的详细信息
  console.log('5. 图片详细信息 (前5张):');
  galleryData.allImages.slice(0, 5).forEach((img, index) => {
    console.log(`  图片 ${index + 1}:`, {
      src: img.src.substring(0, 80) + '...',
      alt: img.alt,
      size: `${img.offsetWidth || '?'} x ${img.offsetHeight || '?'}`
    });
  });
  
  // 恢复原数据
  galleryData = oldGalleryData;
  
  console.log('=== 调试信息结束 ===');
  console.log('💡 提示: 复制上述信息可帮助开发者诊断问题');
  
  return {
    settings,
    diagnostic,
    imageCount: galleryData.allImages ? galleryData.allImages.length : 0
  };
};

// 注意：画廊按钮相关代码已移除，功能集成到弹窗中

// 应用过滤器（原始简单逻辑）
function applyFilter() {
  if (!settings.enableFilter) {
    // 如果禁用过滤，显示所有回答
    document.querySelectorAll('.List-item').forEach(item => {
      item.style.display = '';
    });
    filteredCount = 0;
    return;
  }

  // 获取所有回答
  const answers = document.querySelectorAll('.List-item');
  let hiddenCount = 0;

  answers.forEach(item => {
    const contentElement = item.querySelector('.RichContent');
    if (contentElement && !hasEnoughImages(contentElement)) {
      item.style.display = 'none';
      hiddenCount++;
    } else {
      item.style.display = '';
    }
  });

  filteredCount = hiddenCount;
  // 更新过滤计数
  chrome.runtime.sendMessage({
    type: 'UPDATE_FILTERED_COUNT',
    count: filteredCount
  });
}

// 注意：已移除复杂的防抖更新函数，过滤功能现在使用原始的简单逻辑

// 防抖的自动刷新函数
const debouncedAutoRefresh = debounce(() => {
  if (popupState.isImagesTabActive && popupState.autoRefreshEnabled) {
    console.log('[自动刷新] 触发自动图片刷新');
    collectGalleryData();
    
    // 推送更新的图片数据给弹窗
    chrome.runtime.sendMessage({
      type: 'AUTO_REFRESH_IMAGES',
      images: galleryData.allImages || []
    });
  }
}, 800); // 更长的防抖时间，避免频繁触发

// 滚动监听
let lastScrollTop = 0;
const scrollHandler = () => {
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
  
  // 只有在向下滚动且滚动距离超过一定阈值时才触发
  if (currentScrollTop > lastScrollTop && currentScrollTop - lastScrollTop > 300) {
    debouncedAutoRefresh();
  }
  
  lastScrollTop = currentScrollTop;
};

// 添加滚动监听
addEventListenerWithCleanup(window, 'scroll', scrollHandler, { passive: true });

// 创建MutationObserver监听页面变化（原始简单逻辑）
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.addedNodes.length > 0) {
      applyFilter();
      
      // 如果检测到新内容且弹窗图片标签页激活，也触发自动刷新
      if (popupState.isImagesTabActive && popupState.autoRefreshEnabled) {
        debouncedAutoRefresh();
      }
      break;
    }
  }
});

// 开始监听页面变化
observer.observe(document.body, {
  childList: true,
  subtree: true
});

// 页面卸载时清理资源
function cleanup() {
  try {
    // 停止观察器
    if (observer) {
      observer.disconnect();
    }
    
    // 清理定时器
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    
    // 移除所有事件监听器
    removeAllEventListeners();
    
    // 清理画廊数据
    clearGalleryData();
  } catch (e) {
    console.warn('Cleanup error:', e);
  }
}

// 监听页面卸载事件
addEventListenerWithCleanup(window, 'beforeunload', cleanup);
addEventListenerWithCleanup(window, 'unload', cleanup);

// 定期清理内存（每3分钟）
setInterval(() => {
  try {
    checkMemoryUsage();
    if (galleryData.allImages && galleryData.allImages.length > 500) { // 如果图片过多
      clearGalleryData();
    }
  } catch (e) {
    console.error('定期清理内存时出错:', e);
  }
}, 180000);

// 初始应用过滤器
applyFilter();